package com.netease;

import com.netease.User.Buyer;
import com.netease.User.Seller;
import com.netease.dao.BuyDao;
import com.netease.dao.ProductDao;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by meichen on 2018/3/5.
 */
@Controller
public class ShoppingController
{
    private Buyer buyer;//买家信息
    private Seller seller;//卖家信息
    private HashMap<Integer,Product> allProduct = new HashMap<Integer, Product>();//商品的详细信息
    private List<Buy> allBuy;//已购买商品信息

    @Autowired
    private ProductDao productDao;

    @Autowired
    private BuyDao buyDao;

    /**
     * 未登录首页，完成数据信息初始化，并根据是否有用户登录信息初始化界面的用户信息和商品信息
     * @param request
     * @param map
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/index")
    private String getIndexPage(HttpServletRequest request, ModelMap map)throws IOException{
        initDataInfo();
        Map<String,Object> user = getLoginInfo();
        map.addAttribute("user",user);
        List<Map<String,Object>> productInfo;
        productInfo = getProductList();
        map.addAttribute("productList",productInfo);
        return "index";
    }

    /**
     * 提取表单中的用户名和密码，验证账号和密码是否正确，
     * 如果密码正确，则初始化对应的用户对象信息，并向前台返回一个json格式的数据表示验证通过
     * 如果密码错误，则向前台返回一个非json格式的数据表示验证不通过
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/api/login")
    private String checkLogin(HttpServletRequest request,HttpServletResponse response)throws IOException{
        String userName = request.getParameter("userName");
        String password = request.getParameter("password");
        System.out.println("username: "+  userName + " passord: " + password);
        if(userName.equals("buyer") && password.equals(MD5.getMD5("reyub".getBytes()))){
            resp(response,"{\"result\":0}");
            buyer = new Buyer(0,userName);
            buyer.setLogin(true);
            seller = null;
        }else if(userName.equals("seller") && password.equals(MD5.getMD5("relles".getBytes()))){
            resp(response,"{\"result\":1}");
            seller = new Seller(1,userName);
            seller.setLogin(true);
            buyer = null;
        }else {
            resp(response,"0");
        }
        return "index";
    }

    /**
     * 从参数中获取购买的商品的id，并且在数据库中更新商品的购买信息
     * @param request
     * @return
     */
    @RequestMapping("/api/buy")
    private String payAccount(HttpServletRequest request,HttpServletResponse response)throws IOException{
        int id = Integer.valueOf(request.getParameter("id"));
        productDao.updateSell(id);
        Product p = allProduct.get(id);
        Buy buy = new Buy();
        buy.setPid(id);
        buy.setBuyPrice(p.getPrice());
        buy.setBuyTime(new Date(new java.util.Date().getTime()));
        buyDao.insert(buy);
        initDataInfo();
        resp(response,"{\"result\":0}");
        return "";
    }

    @RequestMapping("/api/delete")
    public String delete(HttpServletRequest request,HttpServletResponse response)throws IOException{
        int id = Integer.valueOf(request.getParameter("id"));
        Product p = allProduct.get(id);
        productDao.delete(p);
        resp(response,"{\"result\":0}");
        return "";
    }

    /**
     * 根据用户的类别来初始化用户首页的商品信息和用户信息
     * @param userType
     * @param map
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/index/{userType}")
    private String getLoginIndex(@PathVariable("userType") String userType, ModelMap map) throws IOException {
        Map<String,Object> user = new HashMap<String, Object>();
        List<Map<String,Object>> productInfo;
        if(userType.equals("buyer") && buyer.isLogin()){
            user.put("usertype",buyer.getUserType());
            user.put("username",buyer.getUserName());
        }else if(userType.equals("seller") && seller.isLogin()){
            user.put("usertype",seller.getUserType());
            user.put("username",seller.getUserName());
        }
        productInfo = getProductList();
        map.addAttribute("productList",productInfo);
        map.addAttribute("user",user);
        return "index";
    }

    //退出登录，根据用户的类别来清空对应账号的登录状态
    @RequestMapping("logout/{username}")
    private String getLogout(@PathVariable("username") String username,ModelMap map){
        if(username.equals("buyer") && buyer.isLogin()){
            buyer = null;
        }else if(username.equals("seller") && seller.isLogin()){
            seller = null;
        }
        List<Map<String,Object>> productInfo = getProductList();
        map.addAttribute("productList",productInfo);
        return "index";
    }

    //进入登录页面
    @RequestMapping("login")
    private String getLoginPage(){
        return "login";
    }

    //进入账户页面
    @RequestMapping("account")
    private String getAccountPage(ModelMap map){
        Map<String,Object> user = getLoginInfo();
        map.addAttribute("user",user);
        List<Map<String,Object>> buyList = new ArrayList<Map<String, Object>>();
        for(Buy buy : allBuy){
            Map<String,Object> buyinfo = new HashMap<String, Object>();
            Product p = allProduct.get(buy.getPid());
            buyinfo.put("id",buy.getPid());
            buyinfo.put("image",p.getImage());
            buyinfo.put("title",p.getTitle());
            long t = new Timestamp(buy.getBuyTime().getTime()).getTime();
            buyinfo.put("buyTime",t);
            buyinfo.put("buyPrice",buy.getBuyPrice());
            buyList.add(buyinfo);
        }
        map.addAttribute("buyList",buyList);
        return "account";
    }

    //进入发布页面
    @RequestMapping("public")
    private String getPublicPage(ModelMap map){
        Map<String,Object> user = getLoginInfo();
        map.addAttribute("user",user);
        return "public";
    }

    /**
     * 获取商人提交的商品信息，并存储到mysql数据库，跳转到提交完成页面并显示提交成功与否
     */
    @RequestMapping(value = "publicSubmit",method = RequestMethod.POST)
    private String getPublicSubmit(HttpServletRequest request,ModelMap map){
        String title = request.getParameter("title");
        String summary = request.getParameter("summary");
        String image = request.getParameter("image");
        String detail = request.getParameter("detail");
        String price = request.getParameter("price");
        Product p = new Product();
        p.setTitle(title);
        p.setSummary(summary);
        p.setImage(image);
        p.setDetail(detail);
        p.setPrice(Double.valueOf(price));
        p.setSold("No");
        productDao.insert(p);
        Map<String,Object> product = new HashMap<String, Object>();
        product.put("id",p.getId());
        product.put("summary",summary);
        product.put("image",image);
        product.put("detail",detail);
        product.put("price",price);
        map.put("product",product);
        if(seller != null){
            Map<String,Object> user = getLoginInfo();
            map.addAttribute("user",user);
        }
        initDataInfo();
        return "publicSubmit";
    }


    @RequestMapping("/show")
    private String getShowPage(HttpServletRequest request,ModelMap map){
        int id = Integer.valueOf(request.getParameter("id"));
        Product pshow = allProduct.get(id);
        Map<String,Object> product = new HashMap<String, Object>();
        product = getProduct(pshow);
        product.put("buyPrice",pshow.getPrice());
        Map<String,Object> user = getLoginInfo();
        map.addAttribute("user",user);
        map.addAttribute("product",product);
        return "show";
    }

    @RequestMapping("/edit")
    public String getEdit(HttpServletRequest request,ModelMap map){
        int id = Integer.valueOf(request.getParameter("id"));
        Product p = allProduct.get(id);
        Map<String,Object> pinfo = getProduct(p);
        map.addAttribute("product",pinfo);
        Map<String,Object> user = getLoginInfo();
        map.addAttribute("user",user);
        return "edit";
    }

    @RequestMapping("/editSubmit")
    public String getEditSubmit(HttpServletRequest request, ModelMap map){
        String title = request.getParameter("title");
        String summary = request.getParameter("summary");
        String image = request.getParameter("image");
        String detail = request.getParameter("detail");
        double price = Double.valueOf(request.getParameter("price"));
        int id = Integer.valueOf(request.getParameter("id"));
        Product productEdit = new Product(id,title,summary,image,detail,price,"No");
        productDao.updateEdit(productEdit);
        initDataInfo();
        Map<String,Object> pinfo = getProduct(productEdit);
        map.addAttribute("product",pinfo);
        Map<String,Object> user = getLoginInfo();
        map.addAttribute("user",user);
        return "show";
    }

    public Map<String,Object> getLoginInfo(){
        Map<String,Object> user = new HashMap<String, Object>();
        if(buyer != null){
            user.put("usertype",buyer.getUserType());
            user.put("username",buyer.getUserName());
        }else if(seller != null){
            user.put("usertype",seller.getUserType());
            user.put("username",seller.getUserName());
        }else {
            user = null;
        }
        return user;
    }

    /**
     *向前台返回数据
     */
    private void resp(HttpServletResponse response,String s)throws IOException{
        response.setStatus(200);
        response.setCharacterEncoding("UTF-8");
        response.flushBuffer();
        PrintWriter printWriter = response.getWriter();
        printWriter.print(s);
        printWriter.flush();
        printWriter.close();
    }

    /**
     * 将商品信息类中的数据，转换成前台freemarker支持的数据形式
     * @return
     */
    private List<Map<String,Object>> getProductList(){
        List<Map<String,Object>> productInfo = new ArrayList<Map<String, Object>>();
        for(Product p : allProduct.values()){
            Map<String,Object> pinfo = getProduct(p);
            productInfo.add(pinfo);
        }
        return productInfo;
    }

    private Map<String,Object> getProduct(Product p){
        Map<String,Object> pinfo = new HashMap<String, Object>();
        pinfo.put("id",p.getId());
        pinfo.put("title",p.getTitle());
        pinfo.put("image",p.getImage());
        pinfo.put("summary",p.getSummary());
        pinfo.put("detail",p.getDetail());
        pinfo.put("price",p.getPrice());
        if(p.getSold().equals("No")){
            pinfo.put("isSell",false);
            pinfo.put("isBuy",false);
        }else {
            pinfo.put("isSell",true);
            pinfo.put("isBuy",true);
        }
        return pinfo;
    }

    //从数据库中获取商品信息
    private void initDataInfo(){
        List<Product> productList= productDao.getAllProdcut();
        for(Product p : productList){
            allProduct.put(p.getId(),p);
        }
        allBuy = buyDao.getAllBuy();
    }
}
